package cn.kgc.shiro.test;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

/**
 * @author: mosin
 * @version: v1.0  2022/5/30
 */
public class CustomerMD5Realm extends AuthorizingRealm {
    //授权
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("授权的方法被调用");
        //获取用户的主身份
        Object primaryPrincipal = principals.getPrimaryPrincipal();
        System.out.println("primaryPrincipal = " + primaryPrincipal);

        // TODO 根据用户的身份信息 查询用户的角色


        //将用户的角色查询后进行封装  AuthorizationInfo
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addRole("root");
        simpleAuthorizationInfo.addRole("customer");

        //设置基于资源的访问权限
        simpleAuthorizationInfo.addStringPermission("order:*:*");
        return simpleAuthorizationInfo;
    }


    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取用户的身份信息
        String principal = (String) token.getPrincipal();
        System.out.println("principal = " + principal);
        //  TODO 根据用户名 查询数据库  user
        if("admin".equals(principal)){
            //将根据用户名从数据库中查询出的用户对象进行封装  AuthenticationInfo   info   ByteSource.Util.bytes("hello") 盐
            return  new SimpleAuthenticationInfo(principal, "496b9aa7d9a9d522dffaba13637e4130", ByteSource.Util.bytes("hello"), this.getName());
        }
        return null;
    }
}
